package com.demo.common.web.filter;

import java.io.*;

import jakarta.servlet.Filter;
import jakarta.servlet.FilterChain;
import jakarta.servlet.FilterConfig;
import jakarta.servlet.ServletException;
import jakarta.servlet.ServletRequest;
import jakarta.servlet.ServletResponse;
import jakarta.servlet.annotation.WebFilter;
import org.springframework.core.annotation.Order;

import com.demo.common.util.RequestContext;
import com.demo.common.util.ThreadContext;

/**
 * ClearContextFilter
 * 
 * @author demo
 * @date 2020-11-13 00:52:18
 */
@Order(Integer.MIN_VALUE)
@WebFilter(value = "/*")
public class ClearContextFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) {
        // Do nothing
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        try {
            chain.doFilter(request, response);
        } finally {
            remove();
        }
    }

    @Override
    public void destroy() {
        remove();
    }

    private void remove() {
        ThreadContext.remove();
        RequestContext.remove();
    }

}
